package com.example.ailiyuncloud.service.Impl;

import com.example.ailiyuncloud.service.SocketService;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: lqj
 * @Date: 2024/05/21/14:34
 * @Description:
 */
@Service
public class SocketServiceImpl implements SocketService {
    @Override
    public Map<String, Object> socketCustom(String username, String message) {
        Map<String, Object> map = new HashMap<>(16);
        try {
            Socket socket = new Socket("localhost", 9002);
            PrintWriter writer = new PrintWriter(socket.getOutputStream());
            writer.println(message);
            writer.flush();
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String response = reader.readLine();
            System.out.println("服务器响应：" + response);
            socket.close();
            map.put(username, "该用户消息发送成功");
            map.put("code", "200");
            map.put("time", System.currentTimeMillis());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public void service() {
        try {
            ServerSocket serverSocket = new ServerSocket(9002);
            System.out.println("服务器启动，等待客户端连接...");

            Socket socket = serverSocket.accept();
            System.out.println("客户端连接成功！");

            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String message = reader.readLine();
            System.out.println("客户端消息：" + message);

            PrintWriter writer = new PrintWriter(socket.getOutputStream());
            writer.println("服务器已收到消息：" + message);
            writer.flush();

            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(9002);
            System.out.println("服务器启动，等待客户端连接...");

            Socket socket = serverSocket.accept();
            System.out.println("客户端连接成功！");

            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String message = reader.readLine();
            System.out.println("客户端消息：" + message);

            PrintWriter writer = new PrintWriter(socket.getOutputStream());
            writer.println("服务器已收到消息：" + message);
            writer.flush();

            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
